package com.alan.dfs.service;

import com.ace.cache.annotation.Cache;
import com.alan.dfs.config.DfsRequire;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author alan
 */
@Service
@Slf4j
public class ZoneFileService {
    /**
     * 文件名前缀
      */
    private static String prefix = "";
    /**
     每次迭代的长度限制，最大1000，推荐值 1000
      */
    private static int limit = 1000;
    /**
     * 指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
     */
    private static String delimiter = "";

    @Autowired
    DfsRequire dfsRequire;

    /**
     * 获取公有文件列表
     * @return
     */
    @Cache(key = "dfs:files{1}")
    public List<FileInfo> getFileList(String zone){
        List<FileInfo> fileInfos = new ArrayList<>();

        if (!StringUtils.isNullOrEmpty(zone)){
            dfsRequire.setBucket(zone);
        }
        BucketManager.FileListIterator fileListIterator =
                dfsRequire.getBucketManager().createFileListIterator(
                        dfsRequire.getBucket(), prefix, limit, delimiter);

        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                item.key = dfsRequire.getDomain() + item.key;
                fileInfos.add(item);
            }
        }
        return fileInfos;
    }
}
